package com.xp.gather2.timer;


import com.xp.gather2.client.LampClient;
import com.xp.gather2.client.LampHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class LampTimer {
     private  LampClient lampClient;

    @Autowired
    public LampTimer( LampClient lampClient) {
       this.lampClient=lampClient;
    }

    /**
     *  第一次延迟1秒执行，上一次开始执行时间点后60秒再次执行；
     */
    @Scheduled(initialDelay = 1000, fixedRate = 1000*60)
    public void lampTasks() {
        int j=0;
        boolean state=true;
        while(state && j < 50){
            if(LampHandler.ISCONNECT){
                for (int i = 1; i < 9; i++) {
                    getLamp(i);
                }
                state=false;
            }else{
                log.info("连接失败"+j);
                sleep();
                j++;
            }
        }
    }

    private void getLamp(int i){
        String sendMsg="dev read 1:1:227 "+i+"|state;\n";
        int lampstate = 0;
        LampHandler.lampID="1:1:227 "+i;
        lampClient.getChannel().writeAndFlush(sendMsg);
        log.info("客户端发送数据 ->" + sendMsg);
        while (LampHandler.STATE && lampstate<50){
            sleep();
            lampstate++;
        }
        LampHandler.STATE=true;
    }
    private void sleep(){
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }



}
